<?php
namespace app\index\domain;

class Page extends BaseList
{
    private $_cache     = [];
    private $_flag      = 'page';
	public function __construct($count)
	{
        $flag = $this->_flag;
        $this->_in    = I('?get.'.$flag)? I('get.'.$flag): 1;
        $this->_count = intval($count);
    }

    /**
     * 获取某个页码的值
     */
    protected function createObj($objParam)
    {
        return $this[$objParam];
    }
    
    /**
     * 自定义获取值
     */
    public function valueGet($key)
    {
        if(!is_numeric($key))
            return null;
        if($key<0)
            $key = $this->_count+$key+1;
        if($key==0)
            $key = $this->_in;
        $result = [
            'text'  => $key,
            'url'   => U('', array_merge($_GET, [$this->_flag=>$key])),
            'type'  => 'num',
            'in'    => false,
        ];
        if($key==$this->_in)
            $result['in'] = true;
        return $result;
    }

    /**
     * 输出省略号
     */
    public function getOmit()
    {
        return [
            'text' => '...',
            'url'  => '#',
            'type'  => 'omit',
            'in'    => false,
        ];
    }

    /**
     * 上一页
     */
    public function getLast()
    {
        return [
            'text' => '<<',
            'url'  => U('', array_merge($_GET, [$this->_flag=>$this->_in-1])),
            'type'  => 'last',
            'in'    => false,
        ];
    }

    /**
     * 下一页
     */
    public function getNext()
    {
        return [
            'text' => '>>',
            'url'  => U('', array_merge($_GET, [$this->_flag=>$this->_in+1])),
            'type'  => 'next',
            'in'    => false,
        ];
    }

    /**
     * 获取分页列表
     */
    protected function getList()
    {
        $count = $this->_count;
        $cacheKey = md5(serialize('contentList'.$count));
        if(isset($this->_cache[$cacheKey]))
            return $this->_cache[$cacheKey];
        $list = [];
        if($this->_count<=1)
            return $this->_cache[$cacheKey] = $list;
        $in = $this->_in;
        if($in!=1)
            $list[] =   'last';
        for($i=1;$i<=$count;$i++){
            if($i>1&& $in-$i>2){
                $list[] = 'omit';
                $i      = $in;
            }
            if($i<$count&& $i-$in>2){
                $list[] = 'omit';
                $i      = $count;
            }
            $list[] = $i;
        }
        if($in!=$count)
            $list[] =   'next';
        if(!empty($list))
            return $this->_cache[$cacheKey] = $list;
        return null;
    }
}

